/**
 * Copyright (C) 2013-2014 EaseMob Technologies. All rights reserved.
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.lianyi.push.util;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningTaskInfo;
import android.app.Dialog;
import android.content.ComponentName;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Build;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;

import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.conn.util.InetAddressUtils;
import org.json.JSONArray;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Field;
import java.net.HttpURLConnection;
import java.net.InetAddress;
import java.net.MalformedURLException;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.URL;
import java.net.URLConnection;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.Enumeration;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

public class CommonUtils {
    private String dayOfMonths;
    private String Birthdays;
    /**
     * 匹配身份证号的正则表达式
     */
    public static final String ID_CARD = "^(^[1-9]\\d{7}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])\\d{3}$)|(^[1-9]\\d{5}[1-9]\\d{3}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])((\\d{4})|\\d{3}[Xx])$)$";
    private static final int TIME_OUT = 3000;
    private static final String ishanzi = "^[A-Za-z0-9\u4e00-\u9fa5]+$";
    /**
     * 正则表达式：验证特殊符号
     */
    public static final String REGEX_Punctuation = "^[A-Za-z0-9\u4e00-\u9fa5]+$";

    /**
     * 检测网络是否可用
     *
     * @param context
     * @return
     */
    public static boolean isNetWorkConnected(Context context) {
        if (context != null) {
            ConnectivityManager mConnectivityManager = (ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo mNetworkInfo = mConnectivityManager
                    .getActiveNetworkInfo();
            if (mNetworkInfo != null) {
                return mNetworkInfo.isAvailable();
            }
        }

        return false;
    }

    /**
     * 检测网络是否可用
     */
    public static boolean Available(Context context) {
        ConnectivityManager connectivity = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connectivity != null) {
            NetworkInfo info = connectivity.getActiveNetworkInfo();
            if (info != null && info.isConnected()) {
                // 当前网络是连接的
                if (info.getState() == NetworkInfo.State.CONNECTED) {
                    // 当前所连接的网络可用
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * ping 的地址
     *
     * @return
     */
    public static boolean ping() {

        String result = null;
        try {
            String ip = "www.baidu.com";// ping 的地址，可以换成任何一种可靠的外网
            Process p = Runtime.getRuntime().exec("ping -c 1 -w 2 " + ip);// ping网址1次
            // 读取ping的内容，可以不加
            InputStream input = p.getInputStream();
            BufferedReader in = new BufferedReader(new InputStreamReader(input));
            StringBuffer stringBuffer = new StringBuffer();
            String content = "";
            while ((content = in.readLine()) != null) {
                stringBuffer.append(content);
            }
            // Log.d("------ping-----result content : " +
            // stringBuffer.toString());
            // ping的状态
            int status = p.waitFor();
            if (status == 0) {
                result = "success";
                return true;
            } else {
                result = "failed";
            }
        } catch (IOException e) {
            result = "IOException";
        } catch (InterruptedException e) {
            result = "InterruptedException";
        } finally {
            // Log.d("----ping---result = " + result);
        }
        return false;

    }

    /**
     * 检测Sdcard是否存在
     *
     * @return
     */
    public static boolean isExitsSdcard() {
        if (android.os.Environment.getExternalStorageState().equals(
                android.os.Environment.MEDIA_MOUNTED))
            return true;
        else
            return false;
    }

    public static String getTopActivity(Context context) {
        ActivityManager manager = (ActivityManager) context
                .getSystemService(Context.ACTIVITY_SERVICE);
        List<RunningTaskInfo> runningTaskInfos = manager.getRunningTasks(1);

        if (runningTaskInfos != null)
            return runningTaskInfos.get(0).topActivity.getClassName();
        else
            return "";
    }

    /**
     * 判断对象或对象数组中每一个对象是否为空: 对象为null，字符序列长度为0，集合类、Map为empty
     *
     * @param obj
     * @return
     */
    public static boolean isNullOrEmpty(Object obj) {
        Log.d("isNullOrEmpty", "obj--->" + obj);

        if (obj != null) {
            Log.d("isNullOrEmpty", "--->not null");
        } else {
            return true;
        }

        if (obj.toString() != null) {// 判断对象（不知道对不对）
            Log.d("isNullOrEmpty", "--->not null");
        } else {
            return true;
        }

		/*
         * if (!isNullOrEmpty(obj.toString())){//判断对象（不知道对不对）0904|好像有错，以后在好好看一下
		 * Log.d("isNullOrEmpty", "=》》》》》》not null"); }else{ return true; }
		 */

        if (obj instanceof CharSequence) {
            Log.d("isNullOrEmpty", "--->CharSequence");
            return ((CharSequence) obj).length() == 0;
        }
        if (obj instanceof Collection) {
            Log.d("isNullOrEmpty", "--->Collection");
            return ((Collection) obj).isEmpty();
        }

        if (obj instanceof Map) {
            Log.d("isNullOrEmpty", "--->Map");
            return ((Map) obj).isEmpty();
        }

        if (obj instanceof Object[]) {
            Log.d("isNullOrEmpty", "--->Object[]");
            Object[] object = (Object[]) obj;
            if (object.length == 0) {
                return true;
            }
            boolean empty = true;
            for (int i = 0; i < object.length; i++) {
                if (!isNullOrEmpty(object[i])) {
                    empty = false;
                    break;
                }
            }
            return empty;
        }

        if (obj instanceof JSONArray) {
            if (((JSONArray) obj).length() == 0) {
                return true;
            }
        }

        if (obj instanceof JSONObject) {
            if (((JSONObject) obj).length() == 0) {
                return true;
            }
        }

        return false;
    }

    /**
     * 计算地球上任意两点(经纬度)距离
     *
     * @param long1 第一点经度
     * @param lat1  第一点纬度
     * @param long2 第二点经度
     * @param lat2  第二点纬度
     * @return 返回距离 单位：米
     */
    public static double Distance(double long1, double lat1, double long2,
                                  double lat2) {
        double a, b, R;
        R = 6378137; // 地球半径
        lat1 = lat1 * Math.PI / 180.0;
        lat2 = lat2 * Math.PI / 180.0;
        a = lat1 - lat2;
        b = (long1 - long2) * Math.PI / 180.0;
        double d;
        double sa2, sb2;
        sa2 = Math.sin(a / 2.0);
        sb2 = Math.sin(b / 2.0);
        d = 2
                * R
                * Math.asin(Math.sqrt(sa2 * sa2 + Math.cos(lat1)
                * Math.cos(lat2) * sb2 * sb2));
        return d;
    }

    /**
     * 过滤emoji 或者 其他非文字类型的字符
     *
     * @param source
     * @return
     */
    public static String filterEmoji(String source) {

        if (!containsEmoji(source)) {
            return source;// 如果不包含，直接返回
        }
        // 到这里铁定包含
        StringBuilder buf = null;

        int len = source.length();

        for (int i = 0; i < len; i++) {
            char codePoint = source.charAt(i);

            if (!isEmojiCharacter(codePoint)) {
                if (buf == null) {
                    buf = new StringBuilder(source.length());
                }

                buf.append(codePoint);
            } else {
            }
        }

        if (buf == null) {
            return "";
        } else {
            if (buf.length() == len) {// 这里的意义在于尽可能少的toString，因为会重新生成字符串
                buf = null;
                return source;
            } else {
                return buf.toString();
            }
        }

    }

    private static boolean isEmojiCharacter(char codePoint) {
        return !((codePoint == 0x0) || (codePoint == 0x9) || (codePoint == 0xA)
                || (codePoint == 0xD)
                || ((codePoint >= 0x20) && (codePoint <= 0xD7FF))
                || ((codePoint >= 0xE000) && (codePoint <= 0xFFFD)) || ((codePoint >= 0x10000) && (codePoint <= 0x10FFFF)));
    }

    /**
     * 检测是否有emoji字符
     *
     * @param source
     * @return 一旦含有就抛出
     */
    public static boolean containsEmoji(String source) {
        // if (StringUtils.isBlank(source)) { //需要引用commons-lang-2.5.jar
        // return false;
        // }

        int len = source.length();

        for (int i = 0; i < len; i++) {
            char codePoint = source.charAt(i);

            if (isEmojiCharacter(codePoint)) {
                // do nothing，判断到了这里表明，确认有表情字符
                return true;
            }
        }

        return false;
    }

    /**
     * 手机号验证
     *
     * @param str
     * @return 验证通过返回true
     */
    public static boolean isMobile(String str) {
        Pattern p = null;
        Matcher m = null;
        boolean b = false;
        p = Pattern.compile("^[1][3,4,5,7,8][0-9]{9}$"); // 验证手机号
        m = p.matcher(str);
        b = m.matches();
        return b;
    }

    /**
     * 导航栏透明
     */
    @SuppressLint("InlinedApi")
    public static void window_transparency(Activity context) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            Window window = context.getWindow();
            window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            // Translucent status bar
            // window.setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS,
            // WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            // Translucent navigation bar
            // window.setFlags(
            // WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION,
            // WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
        }
    }

    /**
     * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
     */
    public static int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    /**
     * 根据手机的分辨率从 px(像素) 的单位 转成为 dp
     */
    public static int px2dip(Context context, float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }

    /**
     * 通过ImageLoader加载及缓存网络图片 　　　* new ImageLoader(RequestQueue queue,ImageCache
     * imageCache) queue：请求队列 imageCache：一个用于图片缓存的接口，一般需要传入它的实现类
     * <p>
     * getImageListener(ImageView view, int defaultImageResId, int
     * errorImageResId) view：ImageView对象 defaultImageResId：默认的图片的资源Id
     * errorImageResId：网络图片加载失败时显示的图片的资源Id
     */
    @SuppressWarnings({"static-access", "unused"})
    public static void VolleyImageLoader(String url, ImageView image) {
        // ImageLoader loader = new ImageLoader(MyApplication.getHttpQueues(),
        // new BitmapCache());
        // ImageListener listener = loader.getImageListener(image,
        // 0, 0);
        // try {
        // // 加载及缓存网络图片
        // loader.get(url, listener);
        // } catch (Exception e) {
        // // TODO: handle exception
        // }

    }

    // 保持dialog不关闭的方法
    public static void keepDialogOpen(Dialog dialog) {
        try {
            Field field = dialog.getClass().getSuperclass()
                    .getDeclaredField("mShowing");
            field.setAccessible(true);
            field.set(dialog, false);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 关闭dialog的方法
    public static void closeDialog(Dialog dialog) {
        try {
            Field field = dialog.getClass().getSuperclass()
                    .getDeclaredField("mShowing");
            field.setAccessible(true);
            field.set(dialog, true);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 验证是否是数字
    public static boolean isNumbers(String str) {
        if (isEmptys(str)) {
            return false;
        } else {
            Pattern p = null;
            Matcher m = null;
            boolean b = false;
            p = Pattern.compile("^[0-9]*$");
            m = p.matcher(str);
            b = m.matches();
            return b;
        }
    }

    // 验证是否为空
    public static boolean isEmptys(String var0) {
        return var0 == null || var0.trim().length() <= 0;
    }

    //判断文件是否存在
    public static boolean fileIsExists(String strFile) {
        try {
            File f = new File(strFile);
            if (!f.exists()) {
                return false;
            }

        } catch (Exception e) {
            return false;
        }

        return true;
    }

    /**
     * 验证给定的字符串是否是身份证号
     * <br>
     * <br>身份证15位编码规则：dddddd yymmdd xx p
     * <br>dddddd：6位地区编码
     * <br>yymmdd：出生年(两位年)月日，如：910215
     * <br>xx：顺序编码，系统产生，无法确定
     * <br>p：性别，奇数为男，偶数为女
     * <br>
     * <br>
     * <br>身份证18位编码规则：dddddd yyyymmdd xxx y
     * <br>dddddd：6位地区编码
     * <br>yyyymmdd：出生年(四位年)月日，如：19910215
     * <br>xxx：顺序编码，系统产生，无法确定，奇数为男，偶数为女
     * <br>y：校验码，该位数值可通过前17位计算获得
     * <br>前17位号码加权因子为 Wi = [ 7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2 ]
     * <br>验证位 Y = [ 1, 0, 10, 9, 8, 7, 6, 5, 4, 3, 2 ]
     * <br>如果验证码恰好是10，为了保证身份证是十八位，那么第十八位将用X来代替 校验位计算公式：Y_P = mod( ∑(Ai×Wi),11 )
     * <br>i为身份证号码1...17 位; Y_P为校验码Y所在校验码数组位置
     *
     * @param string
     * @return
     */
    public static boolean isIdCard(String string) {
        return string.matches(ID_CARD);
//        return IdcardValidator.validate18Idcard(string);
    }

    /**
     * 判断service是否运行
     *
     * @param context
     * @param className
     * @return
     */
    public static boolean isServiceExisted(Context context, String className) {
        ActivityManager activityManager = (ActivityManager) context
                .getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningServiceInfo> serviceList = activityManager
                .getRunningServices(Integer.MAX_VALUE);

        if (!(serviceList.size() > 0)) {
            return false;
        }

        for (int i = 0; i < serviceList.size(); i++) {
            ActivityManager.RunningServiceInfo serviceInfo = serviceList.get(i);
            ComponentName serviceName = serviceInfo.service;

            if (serviceName.getClassName().equals(className)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 远程保存
     */
    public static String PostData(String urlString, String param) {
//        LogUtil.i("测试POST地址:", urlString + "测试请求的参数：" + param);
        StringBuffer sb = new StringBuffer();
        URL url = null;
        HttpURLConnection connection = null;
        DataOutputStream out = null;
        BufferedReader in = null;
        try {
            url = new URL(urlString);

            // 关键代码
            // ignore https certificate validation |忽略 https 证书验证
            if (url.getProtocol().toUpperCase().equals("HTTPS")) {
                trustAllHosts();
                HttpsURLConnection https = (HttpsURLConnection) url
                        .openConnection();
                https.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
                connection = https;
            } else {
                connection = (HttpURLConnection) url.openConnection();
            }
            connection.setReadTimeout(TIME_OUT);
            connection.setDoInput(true);
            connection.setDoOutput(true);
            connection.setRequestMethod("POST");
            connection.setUseCaches(false);
            connection.setInstanceFollowRedirects(true);
            connection.setRequestProperty("Content-Type",
                    "application/x-www-form-urlencoded");
            connection.connect();
            out = new DataOutputStream(connection.getOutputStream());
            out.write(param.getBytes());
            out.flush();

            in = new BufferedReader(new InputStreamReader(
                    connection.getInputStream()), 512);
            String line;
            while ((line = in.readLine()) != null) {
                sb.append(line.trim());
            }
            if (sb.toString().length() < 10) {
                Log.e("测试sb.toString()==", sb.toString() + "==");
                sb.append("{\"result\":\"fail\",\"msg\":\"发送POST请求出现IO异常\",\"data\":\"\"}");
            }
        } catch (IOException e) {
            e.printStackTrace();
            sb.append("{\"result\":\"fail\",\"msg\":\"发送POST请求出现IO异常\",\"data\":\"\"}");
        } catch (Exception e) {
            e.printStackTrace();
            sb.append("{\"result\":\"fail\",\"msg\":\"发送POST请求出现EX异常\",\"data\":\"\"}");
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                }
            }
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                }
            }
            if (connection != null) {
                connection.disconnect();
            }
        }
//        Log.e("测试HTTP Back:", sb.toString());
        return sb.toString();
    }

    @SuppressLint("TrulyRandom")
    public static void trustAllHosts() {
        // Create a trust manager that does not validate certificate chains
        // Android use X509 cert
        TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager() {
            public X509Certificate[] getAcceptedIssuers() {
                return new X509Certificate[]{};
            }

            public void checkClientTrusted(X509Certificate[] chain,
                                           String authType) throws CertificateException {
            }

            public void checkServerTrusted(X509Certificate[] chain,
                                           String authType) throws CertificateException {
            }
        }};

        // Install the all-trusting trust manager
        try {
            SSLContext sc = SSLContext.getInstance("TLS");
            sc.init(null, trustAllCerts, new java.security.SecureRandom());
            HttpsURLConnection
                    .setDefaultSSLSocketFactory(sc.getSocketFactory());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 十六进制转ASCII码
     *
     * @param hex
     * @return
     */
    public static String convertHexToString(String hex) {
        StringBuilder sb = new StringBuilder();
        StringBuilder temp = new StringBuilder();
        for (int i = 0; i < hex.length() - 1; i += 2) {
            String output = hex.substring(i, (i + 2));
            int decimal = Integer.parseInt(output, 16);
            sb.append((char) decimal);
            temp.append(decimal);
        }
        return sb.toString();
    }

    /**
     * 通过身份证计算年龄
     *
     * @param ID_CARD
     * @return
     */
    public static int getuserage(String ID_CARD) {
        if (TextUtils.isEmpty(ID_CARD) || ID_CARD.length() == 0 || ID_CARD.length() != 18) {
            return -1;
        }
        SimpleDateFormat format = new SimpleDateFormat("yyyy",
                Locale.getDefault());
        String time = format.format(new Date(System
                .currentTimeMillis()));
        String year = ID_CARD.substring(6, 10);
        int age = Integer.parseInt(time)
                - Integer.parseInt(year);
        return age;
    }

    /**
     * 验证是否存在
     *
     * @param name
     * @return
     */
    public static boolean isHanzi(String name) {
        return name.matches(ishanzi);
    }

    /**
     * 校验特殊符号，只能是字母、数字、汉字
     *
     * @param punctuation
     * @return 校验通过返回true，否则返回false
     */
    public static boolean isPunctuation(String punctuation) {
        return Pattern.matches(REGEX_Punctuation, punctuation);
    }

    /**
     * 数字验证
     *
     * @param str
     * @return
     */
    public static boolean isDigital(String str) {
        return str.matches("^[0-9]*$");
    }


    /**
     * 将字符串转换成二进制字符串
     *
     * @param str
     * @return
     */
    public static String StrToBinstr(String str) {
        char[] strChar = str.toCharArray();
//        String result = "";
        StringBuffer stringBuffer = new StringBuffer();
        for (int i = 0; i < strChar.length; i++) {
            stringBuffer.append(Integer.toBinaryString(strChar[i]));
//            result += Integer.toBinaryString(strChar[i]);
        }
        return stringBuffer.toString();
    }

    /**
     * @param birthDayStr
     * @return
     * @throws Exception String
     * @方法名称: getAge
     * @方法描述: 根据当前日期获取年龄
     * @Date : 2017-12-19
     */
    public static String getAge(String birthDayStr) throws Exception {

        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        format.setLenient(false);
        Date birthDay = format.parse(birthDayStr);
        Calendar calBir = Calendar.getInstance();
        calBir.setTime(birthDay);
        // 获取当前系统时间
        Calendar cal = Calendar.getInstance();
        // 如果出生日期大于当前时间，则抛出异常
        if (cal.before(calBir)) {
            throw new IllegalArgumentException(
                    "The birthDay is before Now.It's unbelievable!");
        }
        // 取出系统当前时间的年、月、日部分
        int yearNow = cal.get(Calendar.YEAR);
        int monthNow = cal.get(Calendar.MONTH) + 1;
        int dayOfMonthNow = cal.get(Calendar.DAY_OF_MONTH);

        // 取出出生日期的年、月、日部分
        int yearBirth = calBir.get(Calendar.YEAR);
        int monthBirth = calBir.get(Calendar.MONTH) + 1;
        int dayOfMonthBirth = calBir.get(Calendar.DAY_OF_MONTH);
        String resAge = "";
        // 如果当前年份大于生日年份
        if (yearNow > yearBirth) {
            int age = yearNow - yearBirth;
            // 如果当前年比生日年份大一年
            if (yearNow - yearBirth == 1) {
                //如果为临近一个月  2017-12-31/2018-01-01
                if ((monthNow + 11) == monthBirth) {
                    if (dayOfMonthBirth > dayOfMonthNow) {
                        resAge = ((calBir.getActualMaximum(Calendar.DATE) - (dayOfMonthBirth - dayOfMonthNow)) + 1)
                                + "天";
                    } else {
                        // 如果当前日期不小于生日日期 则为1月
                        resAge = "1个月";
                    }
                } else if (monthNow < monthBirth) {// 如果当前月份比生日月份小 说明不满一年 计算月份
                    resAge = (12 - (monthBirth - monthNow) + 1) + "个月";
                } else {
                    // 如果当前月份不小于生日月份 则为1岁
                    resAge = "1岁";
                }
            } else {// 如果当前年份比生日年份超出1年一年以上 则计算岁
                // 如果当前月份比生日月份小，说明不满整岁，减去一岁
                if ((monthNow < monthBirth)) {
                    resAge = (age - 1) + "岁";
                } else if ((monthNow == monthBirth) && (dayOfMonthNow < dayOfMonthBirth)) {//如果当前月份等于生日月份，并且当前日期小于生日日期，说明不满整岁，减去一岁
                    resAge = (age - 1) + "岁";
                } else {
                    resAge = age + "岁";
                }
            }
        } else if (yearNow == yearBirth) {// 如果当前年份相同
            int age = 0;
            // 如果当前月份比生日月份大
            if (monthNow > monthBirth) {
                age = monthNow - monthBirth;
                // 如果当前月份只比生日月份大一月
                if (monthNow - monthBirth == 1) {
                    // 如果当前日期比生日日期小 则计算天数
                    if (dayOfMonthBirth > dayOfMonthNow)
                        resAge = ((calBir.getActualMaximum(Calendar.DATE) - (dayOfMonthBirth - dayOfMonthNow)) + 1)
                                + "天";
                    else
                        // 如果当前日期不小于生日日期 则为1月
                        resAge = "1个月";
                } else {
                    // 如果当前月份只比生日月份大不止1月 则计算月份
                    resAge = (age + 1) + "个月";
                }
            } else if (monthNow == monthBirth) {// 如果当前月份等于生日月份 则计算天数
                int ages = dayOfMonthNow - dayOfMonthBirth;
                resAge = (ages + 1) + "天";
            }
        }
        System.out.println("age:" + resAge);
        return resAge + "";
    }

    /**
     * 限制最多输入小数点后两位
     *
     * @param editText
     */
    public static void setPricePoint(final EditText editText) {
        editText.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before,
                                      int count) {
                if (s.toString().contains(".")) {
                    if (s.length() - 1 - s.toString().indexOf(".") > 2) {
                        s = s.toString().subSequence(0,
                                s.toString().indexOf(".") + 3);
                        editText.setText(s);
                        editText.setSelection(s.length());
                    }
                }
                if (s.toString().trim().substring(0).equals(".")) {
                    s = "0" + s;
                    editText.setText(s);
                    editText.setSelection(2);
                }

                if (s.toString().startsWith("0")
                        && s.toString().trim().length() > 1) {
                    if (!s.toString().substring(1, 2).equals(".")) {
                        editText.setText(s.subSequence(0, 1));
                        editText.setSelection(1);
                        return;
                    }
                }
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                                          int after) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                // TODO Auto-generated method stub

            }

        });

    }

    /**
     * 获取外网ip
     *
     * @return
     */
    public static String getNetIp() {
        URL infoUrl = null;
        InputStream inStream = null;
        String ipLine = "";
        HttpURLConnection httpConnection = null;
        try {
            infoUrl = new URL("http://ip.chinaz.com/getip.aspx");
            URLConnection connection = infoUrl.openConnection();
            httpConnection = (HttpURLConnection) connection;
            int responseCode = httpConnection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                inStream = httpConnection.getInputStream();
                BufferedReader reader = new BufferedReader(
                        new InputStreamReader(inStream, "utf-8"));
                StringBuilder strber = new StringBuilder();
                String line = null;
                while ((line = reader.readLine()) != null) {
                    strber.append(line + "\n");
                }
                Pattern pattern = Pattern
                        .compile("((?:(?:25[0-5]|2[0-4]\\d|((1\\d{2})|([1-9]?\\d)))\\.){3}(?:25[0-5]|2[0-4]\\d|((1\\d{2})|([1-9]?\\d))))");
                Matcher matcher = pattern.matcher(strber.toString());
                if (matcher.find()) {
                    ipLine = matcher.group();
                }
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                inStream.close();
                httpConnection.disconnect();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
        Log.e("getNetIp", ipLine);
        return ipLine;
    }

    /**
     * 得到本机IP地址
     *
     * @return
     */
    public static String getLocalIpAddress() {
        try {
            // 获得当前可用的wifi网络
            Enumeration<NetworkInterface> en = NetworkInterface
                    .getNetworkInterfaces();
            while (en.hasMoreElements()) {
                NetworkInterface nif = en.nextElement();
                Enumeration<InetAddress> enumIpAddr = nif.getInetAddresses();
                while (enumIpAddr.hasMoreElements()) {
                    InetAddress mInetAddress = enumIpAddr.nextElement();
                    if (!mInetAddress.isLoopbackAddress()
                            && InetAddressUtils.isIPv4Address(mInetAddress
                            .getHostAddress())) {
                        return mInetAddress.getHostAddress();
                    }
                }
            }
        } catch (SocketException e) {
            e.printStackTrace();
//            ToastUtil.showShortToast("获取本机IP地址失败");
            LogUtil.e("获取本机IP地址失败", "获取本机IP地址失败");
        }
        return "";
    }

}
